//
//  SelectGoodsNameVC.m
//  NtoccShipper
//
//  Created by mac on 2019/12/2.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "SelectGoodsNameVC.h"
#import "SelectGoodsNameCell.h"
#import "SelectGoodsNameHeaderModel.h"
#import "SelectGoodsNameCellModel.h"

@interface SelectGoodsNameVC ()<UITableViewDelegate,UITableViewDataSource>{
    UIView* _imgParent;
    int indexHedaer;  // 记录图片的位置
    int indexSelect;
}
@property (nonatomic,strong) CJTableView *tableView;
@property (nonatomic,strong) SelectGoodsNameCell *selectGoodsNameCell;

@property (nonatomic,strong) NSMutableArray *arrHeaderTitle;
@property (nonatomic,strong) NSMutableArray *arrCellModel;

@property (weak, nonatomic) IBOutlet UIButton *btnSave;

@end

@implementation SelectGoodsNameVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitleName:CJLString(@"选择货物名称")];
    [self setBackLeftButton:@""];
    [self initData];
    self.btnSave.backgroundColor = [UIColor cjMainColor];
    self.selectGoodsNameCell = [[SelectGoodsNameCell alloc]initWithFlex:nil reuseIdentifier:nil];
    [self.view addSubview:self.tableView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self loadData];
    
}
- (void)initData{
    self.arrHeaderTitle = [[NSMutableArray alloc]initWithCapacity:3];
    self.arrCellModel = [[NSMutableArray alloc]init];
}
- (void)loadData{
    
    NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/goodsType",CJBaseUrl);
    NSDictionary *dicPra = @{
        @"parentCode":@"goodsBigType"
    };
    
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strUrl parameters:dicPra success:^(id  _Nonnull responseObject) {
        
        DLog(@"++++++++%@",responseObject);

        NSArray *list = responseObject[@"records"];
        [self.arrHeaderTitle  removeAllObjects];
        if (list.count > 0) {
            
            for (int i = 0; i < list.count ; i++) {
                NSDictionary *dic = list[i];
                NSError *error;
                SelectGoodsNameHeaderModel *model = [[SelectGoodsNameHeaderModel alloc]initWithDictionary:dic error:&error];
                model.selected = NO;
                model.isNilOrNull = YES;
                model.location = @"10000";
                model.isCreate = NO;

                [self.arrHeaderTitle addObject:model];
                
            }
            [ws createTableViewHeaderView];
            
            if ([self.dictData isKindOfClass:[NSNull class]] || [self.dictData isEqual:[NSNull null]] || self.dictData.count == 0) {
                
            }else{
                [self.arrCellModel removeAllObjects];
                self.arrCellModel = (NSMutableArray *)self.dictData[@"cellInfo"];
                NSString *strIndex =  self.dictData[@"index"];
                
                 UIView* cell1 = [_imgParent viewWithTag:100 + strIndex.intValue];
                 UILabel *label1 = (UILabel *)[cell1 viewWithTag:1000 + cell1.tag - 100];
                 cell1.backgroundColor = [UIColor cjMainColor];
                 label1.textColor = [UIColor cjWhiteColor];
                SelectGoodsNameHeaderModel *modSelect = self.arrHeaderTitle[strIndex.intValue];
                modSelect.selected = YES;
                [ws.tableView reloadData];
            }
            
        }
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

-(void)removeCell:(UIGestureRecognizer*)sender
{
    UIView* cell = sender.view;
    UILabel *label = (UILabel *)[cell viewWithTag:1000 + cell.tag - 100];
    indexHedaer = (int )(cell.tag -100);
    SelectGoodsNameHeaderModel *mode = self.arrHeaderTitle[cell.tag - 100];
  
    // 首先清除
    [self.arrCellModel removeAllObjects];
    
//    DLog(@"++++++ %d",indexHedaer);
//    DLog(@"=======上次选中 %d",indexSelect)
    
    if ([self.dictData isKindOfClass:[NSNull class]] || [self.dictData isEqual:[NSNull null]] || self.dictData.count == 0) {
        
    }else{

        NSString *strIndex =  self.dictData[@"index"];
        UIView* cell1 = [_imgParent viewWithTag:100 + strIndex.intValue];
        UILabel *label1 = (UILabel *)[cell1 viewWithTag:1000 + cell1.tag - 100];
        cell1.backgroundColor = [UIColor cjWhiteColor];
        label1.textColor = [UIColor cjMainTextColor];
        SelectGoodsNameHeaderModel *modSelect = self.arrHeaderTitle[strIndex.intValue];
        modSelect.selected = NO;
    }

    if (indexSelect != indexHedaer) {
        SelectGoodsNameHeaderModel *modSelect = self.arrHeaderTitle[indexSelect];
        modSelect.selected = NO;
        
        UIView* cell1 = [_imgParent viewWithTag:100 + indexSelect];
        UILabel *label1 = (UILabel *)[cell1 viewWithTag:1000 + cell1.tag - 100];
        cell1.backgroundColor = [UIColor cjWhiteColor];
        label1.textColor = [UIColor cjMainTextColor];

    }
    
    if (mode.selected) {
        mode.selected = NO;
        cell.backgroundColor = [UIColor cjWhiteColor];
        label.textColor = [UIColor cjMainTextColor];

        [self.tableView reloadData];

    }else{
        mode.selected = YES;
        indexSelect = (int )(cell.tag -100);
        cell.backgroundColor = [UIColor cjMainColor];
        label.textColor = [UIColor cjWhiteColor];
        [self getDataWithCode:mode.code  withUserCarTypeHeaderModel:mode];
    }
   
}

- (void)getDataWithCode:(NSString *)strCode withUserCarTypeHeaderModel:(SelectGoodsNameHeaderModel *)mod{
        NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/goodsType",CJBaseUrl);
        NSDictionary *dicPra = @{
            @"parentCode":strCode
        };
        
        WS(ws);
        [[HDNetworking sharedHDNetworking] GET:strUrl parameters:dicPra success:^(id  _Nonnull responseObject) {
            
            DLog(@"++++++++%@",responseObject);
            NSString *total = CJStringWithFormat(@"%@",responseObject[@"total"]);
           
            if (total.intValue == 0) {
                
            }else{
                
                NSArray *list = responseObject[@"records"];
                NSMutableArray *arrList = [[NSMutableArray alloc]init];
                if (list.count > 0) {
    
                    for (int i = 0; i < list.count ; i++) {
                        NSDictionary *dic = list[i];
                        NSError *error;
                        SelectGoodsNameCellModel *model = [[SelectGoodsNameCellModel alloc]initWithDictionary:dic error:&error];
                        model.selected = NO;
                        [arrList addObject:model];
    
                    }
                }
                mod.location = CJStringWithFormat(@"%lu",(unsigned long)self.arrCellModel.count);
                mod.isNilOrNull = NO;
                [self.arrCellModel addObject:arrList];
               
            }
            [ws.tableView reloadData];
            
        } failure:^(NSError * _Nonnull error) {
            
        }];
    
}

- (void)createTableViewHeaderView{

    //    WS(ws);
    CGRect rcFrame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 0);
    FlexFrameView *header = [[FlexFrameView alloc] initWithFlex:@"SelectGoodsNameHeaderView" Frame:rcFrame Owner:self];
    header.flexibleHeight = YES;

      for (int i =0; i < self.arrHeaderTitle.count; i++) {
              
          UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeCell:)];
          UIView* cell = [[UIView alloc]init];
          cell.tag = i + 100;

          [cell enableFlexLayout:YES];
          [cell addGestureRecognizer:tap];

          [cell setLayoutAttrStrings:@[
                                       @"minHeight",@"30",
                                       @"margin",@"1.5%",
                                       @"alignItems",@"center",
                                       @"justifyContent",@"center",
                                       ]];
          [cell setViewAttr:@"borderRadius" Value:@"5"];
          [cell setViewAttr:@"borderWidth" Value:@"0.5"];
          [cell setViewAttr:@"borderColor" Value:@"#E4E9ED"];

          UILabel *lab = [[UILabel alloc]init];
          lab.tag = 1000 + i;
          [lab enableFlexLayout:YES];
          [lab setLayoutAttrStrings:@[
                                 @"flex",@"1",
                                 ]];

          [cell addSubview:lab];
//          [lab setViewAttr:@"textAlign" Value:@"center"];
          [lab setViewAttr:@"fontSize" Value:@"14"];
          [lab setViewAttr:@"color" Value:@"#434C67"];

          SelectGoodsNameHeaderModel *mode = self.arrHeaderTitle[i];
          lab.text = CJStringWithFormat(@"  %@  ",mode.name);
          NSAttributedString * attR = [[NSAttributedString alloc] initWithString:lab.text attributes:@{NSFontAttributeName: lab.font,NSBaselineOffsetAttributeName:@(2)}];
          [lab setAttributedText:attR];

          [cell markDirty];
          [_imgParent insertSubview:cell atIndex:0];

          [_imgParent markDirty];
          [header layoutIfNeeded];
              
        }
        
        [header layoutIfNeeded];
        self.tableView.tableHeaderView = header;
        [self.tableView reloadData];
}

- (IBAction)btnSaveAction:(id)sender {
    
    NSString *strSelect = @"";
    if (self.arrCellModel.count > 0) {
        
        BOOL selelctSmall = NO;

        for (int i = 0; i < self.arrCellModel.count; i++) {
            
            NSMutableArray *array = self.arrCellModel[i];
            
            if (array.count > 0) {
                
                
                for (int y = 0; y < array.count; y++) {
                    SelectGoodsNameCellModel *model = array[y];
                    
                    if (model.selected) {
                        strSelect = CJStringWithFormat(@"%@,%@",strSelect,model.name);
                        selelctSmall = YES;
                    }
                }
            }
            
        }
    
        
        // 获取选中的 大类
        SelectGoodsNameHeaderModel *modBig = self.arrHeaderTitle[indexHedaer];
        
        if (selelctSmall) {
            NSDictionary *dic = @{
                @"cellInfo":self.arrCellModel,
                @"index":CJStringWithFormat(@"%d",indexHedaer),
                @"coalBigType":modBig.code,
                @"name":modBig.name
            };

            if (self.blockSelectInfo) {
                self.blockSelectInfo(dic);
            }

            [self pop];
        }else{
            [CJAlert showStringDismissWithDelay:@"请选择小类"];

        }
        
    }else{
        
        [CJAlert showStringDismissWithDelay:@"请选择分类"];
    }
}


#pragma mark----tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    return self.arrNewsList.count;
    return self.arrCellModel.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    static NSString *identifier = @"SelectGoodsNameCell";
     SelectGoodsNameCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
     if (cell == nil) {
         cell = [[SelectGoodsNameCell alloc] initWithFlex:nil reuseIdentifier:identifier];
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
//         [cell setCellInfoWithDic:nil];
     }
    SelectGoodsNameHeaderModel *model = self.arrHeaderTitle[indexHedaer];
    [cell setCellInfoWithMutaArray:self.arrCellModel[indexPath.row] withHeaderModel:model];
     return cell;
}

- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, kTopHeight + CJTableToTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight - self.btnSave.height - CJTableToTopHeight),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
//        .tbMjHeadFooter(YES)
        ;
//        WS(ws);
//        _tableView.blockMjHeader = ^(BOOL isheader) {
//
//            if (isheader) {
//                [ws downRefresh];
//            } else {
//                [ws upRefresh];
//            }
//
//        };

    }
    
    return _tableView;
}
@end
